package com.tarzan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarzan.api.model.request.user.InserUserInfoReq;
import com.tarzan.api.model.request.user.SysUserIdReq;
import com.tarzan.api.model.request.user.SysUserInfoReq;
import com.tarzan.api.model.request.user.UpdateUserInfoReq;
import com.tarzan.api.model.response.user.SysUserDetailInfoResp;
import com.tarzan.api.model.response.user.SysUserInfoResp;
import com.tarzan.api.model.response.user.UserRolePermissionsInfoResp;
import com.tarzan.common.core.exception.BusinessException;
import com.tarzan.common.core.exception.ErrorCodesEnum;
import com.tarzan.system.dao.SysUserMapper;
import com.tarzan.system.entity.SysRole;
import com.tarzan.system.entity.SysUser;
import com.tarzan.system.service.ISysMenuService;
import com.tarzan.system.service.ISysRoleService;
import com.tarzan.system.service.ISysUserRoleService;
import com.tarzan.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liujinshan
 * @title: SysUserServiceImpl
 * @projectName tarzan-cloud
 * @description: TODO
 * @date 2021-5-19 21:41
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    private final static Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ISysMenuService iSysMenuService;

    @Autowired
    private ISysUserRoleService iSysUserRoleService;

    /**
     * 根据id 查询用户信息
     * @param sysUserIdReq
     * @return
     */
    @Override
    public SysUserInfoResp getUserInfoById(SysUserIdReq sysUserIdReq) {

        Long id = Optional.ofNullable(sysUserIdReq).map(SysUserIdReq::getId).orElse(null);
        if (null == id) {
            throw new BusinessException(ErrorCodesEnum.REQUEST_PARAM_NOT_EMPTY_ERROR.code(),ErrorCodesEnum.REQUEST_PARAM_NOT_EMPTY_ERROR.msg());
        }
        SysUserInfoResp sysUserInfoResp = new SysUserInfoResp();
        SysUser sysUser = new SysUser();
        try {
            sysUser = sysUserMapper.selectById(id);

        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> getUserInfoById()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.QUERY_USER_INFO_ERROR.code(),ErrorCodesEnum.QUERY_USER_INFO_ERROR.msg());
        }
        try {
            BeanUtils.copyProperties(sysUser,sysUserInfoResp);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> getUserInfoById()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.REF_ERROR.code(),ErrorCodesEnum.REF_ERROR.msg());
        }
        return sysUserInfoResp;
    }
    /**
     * 分页查询
     * @param sysUserInfoReq
     * @return
     */
    @Override
    public IPage<SysUserInfoResp> getPageUserInfo(SysUserInfoReq sysUserInfoReq) {

        Long  currentPage = Optional.ofNullable(sysUserInfoReq).map(SysUserInfoReq::getCurrentPage).orElse(null);
        Long  pageSize = Optional.ofNullable(sysUserInfoReq).map(SysUserInfoReq::getPageSize).orElse(null);
        String  userName = Optional.ofNullable(sysUserInfoReq).map(SysUserInfoReq::getUserName).orElse(null);
        String  phone = Optional.ofNullable(sysUserInfoReq).map(SysUserInfoReq::getPhone).orElse(null);
        Integer  status = Optional.ofNullable(sysUserInfoReq).map(SysUserInfoReq::getStatus).orElse(null);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (null != userName && !"".equals(userName)) {
            queryWrapper.like("user_name",userName);
        }
        if (null != phone && !"".equals(phone)) {
            queryWrapper.like("phone",phone);
        }
        if (null != status && !"".equals(status)) {
            queryWrapper.eq("status",status);
        }
        IPage page = new Page(currentPage,pageSize);
        try {
            page = sysUserMapper.selectPage(page,queryWrapper);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> getPageUserInfo()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.QUERY_USER_INFO_ERROR.code(),ErrorCodesEnum.QUERY_USER_INFO_ERROR.msg());
        }
        return page;
    }

    /**
     * 新增用户
     * @param inserUserInfoReq
     */
    @Override
    public void insert(InserUserInfoReq inserUserInfoReq) {
        SysUser sysUser = new SysUser();
        try {
            BeanUtils.copyProperties(inserUserInfoReq, sysUser);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> insert()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.REF_ERROR.code(),ErrorCodesEnum.REF_ERROR.msg());
        }
        try {
            sysUserMapper.insert(sysUser);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> insert()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.INSERT_USER_INFO_ERROR.code(),ErrorCodesEnum.INSERT_USER_INFO_ERROR.msg());
        }

    }

    /**
     * 更新用户信息
     *
     * @param updateUserInfoReq
     */
    @Override
    public void update(UpdateUserInfoReq updateUserInfoReq) {

        Long id = Optional.ofNullable(updateUserInfoReq).map(UpdateUserInfoReq::getId).orElse(null);
        if (null == id) {
            throw new BusinessException(ErrorCodesEnum.REQUEST_PARAM_NOT_EMPTY_ERROR.code(),ErrorCodesEnum.REQUEST_PARAM_NOT_EMPTY_ERROR.msg());
        }
        SysUser sysUser = new SysUser();
        try {
            BeanUtils.copyProperties(updateUserInfoReq, sysUser);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> updateById()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.REF_ERROR.code(),ErrorCodesEnum.REF_ERROR.msg());
        }
        try {
            sysUserMapper.updateById(sysUser);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> updateById()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.UPDATE_USER_INFO_ERROR.code(),ErrorCodesEnum.UPDATE_USER_INFO_ERROR.msg());
        }
    }

    /**
     * 删除用户信息
     *
     * @param sysUserIdReq
     */
    @Override
    public void delete(SysUserIdReq sysUserIdReq) {
        Long id = Optional.ofNullable(sysUserIdReq).map(SysUserIdReq::getId).orElse(null);
        if (null == id) {
            throw new BusinessException(ErrorCodesEnum.REQUEST_PARAM_NOT_EMPTY_ERROR.code(),ErrorCodesEnum.REQUEST_PARAM_NOT_EMPTY_ERROR.msg());
        }
        try {
            sysUserMapper.deleteById(id);
        } catch (Exception e) {
            logger.error("SysUserServiceImpl -> deleteById()  EXECUTE ERROR :"+e);
            throw new BusinessException(ErrorCodesEnum.DELETE_USER_INFO_ERROR.code(),ErrorCodesEnum.DELETE_USER_INFO_ERROR.msg());
        }
    }

    /**
     * 查询该用户是否存在
     *
     * @param userName
     * @return
     */
    @Override
    public SysUser findByuserName(String userName) {
        return sysUserMapper.findByuserName(userName);
    }

    /**
     * 查询该用户权限
     *
     * @param userName
     * @return
     */
    @Override
    public Set<String> findPermissions(String userName) {
        return null;
    }

    /**
     * 获取用户基本信息、角色信息、权限信息
     *
     * @param userName
     * @return
     */
    @Override
    public UserRolePermissionsInfoResp getUserInfo(String userName) {
        UserRolePermissionsInfoResp userRolePermissionsInfoResp = new UserRolePermissionsInfoResp();
        SysUser user = sysUserMapper.findByuserName(userName);
        if (null == user) {
            throw new BusinessException(ErrorCodesEnum.USER_DOES_NOT_EXIST_ERROR.code(),ErrorCodesEnum.USER_DOES_NOT_EXIST_ERROR.msg());
        }
        List<SysRole> roles = iSysRoleService.findRoleByUserId(user);
        List<String> roleNameList = roles.stream().map(item -> item.getRoleName()).collect(Collectors.toList());
        if(roleNameList.size() == 0) {
            //前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
            roleNameList.add("");
        }
        SysUserInfoResp userInfoResp = new SysUserInfoResp();
        BeanUtils.copyProperties(user,userInfoResp);
        List<String> permissionValueList = iSysMenuService.selectMenuPermsByUserId(user.getId());
        userRolePermissionsInfoResp.setUserName(userName);
        userRolePermissionsInfoResp.setSysUser(userInfoResp);
        userRolePermissionsInfoResp.setRoles(roleNameList);
        userRolePermissionsInfoResp.setPermissions(permissionValueList);
        return userRolePermissionsInfoResp;
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void deleteBatchByIds(List ids) {
        sysUserMapper.deleteBatchIds(ids);
    }

    /**
     * @param username
     * @return com.tarzan.api.model.response.user.SysUserInfoResp
     * @title findUserInfoByUserName
     * @description TODO 根据用户名称查询用户信息
     * @author liujinshan
     * @data 2021/7/1 15:48
     */
    @Override
    public SysUserDetailInfoResp findUserInfoByUserName(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name",username);
        SysUser sysUser = baseMapper.selectOne(queryWrapper);
        SysUserDetailInfoResp sysUserDetailInfoResp = new SysUserDetailInfoResp();
        BeanUtils.copyProperties(sysUser,sysUserDetailInfoResp);
        return sysUserDetailInfoResp;
    }
}
